from django.shortcuts import render,redirect
from app01 import models

def login(request):
    """
    用户登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'login.html')

    # 获取用户提交的用户名和密码
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')

    # 去数据库检查用户名密码是否正确
    # user_object = models.UserInfo.objects.filter(username=user,password=pwd).first()
    # user_object = models.UserInfo.objects.filter(username=user, password=pwd).exists()
    user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()

    if user_object:
        # 用户登录成功
        result = redirect('/index/')
        result.set_cookie('xxxxxxxx',user)
        return result

        request.session['user_name'] = user_object.username
        request.session['user_id'] = user_object.pk
        return redirect('/index/')

    # 用户名或密码输入错误
    return render(request,'login.html',{'error':'用户名或密码错误'})


def auth(func):
    def inner(request,*args,**kwargs):
        name = request.session.get('user_name')
        if not name:
            return redirect('/login/')

        return func(request,*args,**kwargs)
    return inner

@auth
def index(request):
    """
    博客后台首页
    :param request:
    :return:
    """
    return render(request,'index.html')
